# from django.shortcuts import render
# from django.http import JsonResponse
# from uuapp.models import *
# cart/views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse
from uuapp.models import User, StockOut, Product, StockIn, StockWarning, Order, ProductCategory, Purchase

from django.shortcuts import render, redirect
from django.http import JsonResponse
<<<<<<< HEAD
from uuapp.models import Product  # 移除对 Goods 模型的引用
# 在 cart/views.py 文件中
from django.shortcuts import render
from uuapp.models import Product, ProductCategory  # 假设 ProductCategory 是商品类别模型

def show_cart(request):
    """
    显示购物车内容和商品列表
    """
    # 获取所有商品
    products = Product.objects.all()
    
    # 获取所有商品类别
    categories = ProductCategory.objects.all()
    
    # 渲染模板并传递上下文数据
    return render(request, 'show_cart.html', {
        'Product_list': products,
        'categories': categories,
    })


def add_to_cart(request):
    """
    Add products to shopping cart.
    """
    product_id = request.GET.get('id')  # 将 goods_id 替换为 product_id
    quantity = int(request.GET.get('quantity', 1))
    
    if not product_id:
        return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'}, status=400)
    
    try:
        product = Product.objects.get(id=product_id)  # 将 Goods 替换为 Product
    except Product.DoesNotExist:
        return JsonResponse({'status': 0, 'errmsg': '商品不存在'}, status=404)
=======
from .models import Cart, CartItem, Product  # 确保从正确的位置导入模型

def api_products(request):
    """
    API endpoint to return product data in JSON format
    """
    products = Product.objects.all().values('product_code', 'name', 'price')
    return JsonResponse(list(products), safe=False)
# cashier
def show_cart(request):
     from .models import ProductCategory, Product

def show_cart(request):
    categories = ProductCategory.objects.all()
    Product_list = Product.objects.filter(stock__gt=0)
    return render(request, 'show_cart.html', {'categories': categories, 'Product_list': Product_list})



# def view_cart(request):  # 重命名视图函数以避免冲突
#     return render(request, 'cart.html')

# def show_cart(request):
#     """
#     Display shopping cart contents
#     """
#     cart = request.session.get('cart', {})
#     cart_items = []
    
#     for goods_id, quantity in cart.items():
#         try:
#             goods = Product.objects.get(id=goods_id)  # 确保使用正确的模型名
#             cart_items.append({
#                 'goods': goods,
#                 'quantity': quantity
#             })
#         except Product.DoesNotExist:
#             continue
    
#     return render(request, 'show_cart.html', {'cart_items': cart_items})

# @login_required
def add_to_cart(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    cart, created = Cart.objects.get_or_create(user=request.user)
>>>>>>> 0ac75087e5e07a3ef0624f7a4a9866c7346941b7
    
    cart_item, created = CartItem.objects.get_or_create(
        cart=cart,
        product=product,
        defaults={'quantity': 1, 'price': product.price}
    )
    
    if not created:
        cart_item.quantity += 1
        cart_item.save()
    
<<<<<<< HEAD
    # Add or update products in cart
    if product_id in cart:
        cart[product_id] += quantity
    else:
        cart[product_id] = quantity
=======
    return redirect('product_detail', id=product_id)

# def cart(request):
#     return render(request, 'cart.html')


# def show_cart(request):
#     """
#     Display shopping cart contents
#     """
#     cart = request.session.get('cart', {})
#     cart_items = []
>>>>>>> 0ac75087e5e07a3ef0624f7a4a9866c7346941b7
    
#     # Get goods details for items in cart
#     for goods_id, quantity in cart.items():
#         try:
#             goods = Goods.objects.get(id=goods_id)
#             cart_items.append({
#                 'goods': goods,
#                 'quantity': quantity
#             })
#         except Goods.DoesNotExist:
#             continue
    
#     return render(request, 'show_cart.html', {'cart_items': cart_items})


# # def add_to_cart(request):
# #     """
# #     Add goods to shopping cart
# #     """
# #     goods_id = request.GET.get('id')
# #     quantity = int(request.GET.get('quantity', 1))
    
# #     if not goods_id:
# #         return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'}, status=400)
    
# #     try:
# #         goods = Goods.objects.get(id=goods_id)
# #     except Goods.DoesNotExist:
# #         return JsonResponse({'status': 0, 'errmsg': '商品不存在'}, status=404)
    
# #     # Initialize cart in session if not exists
# #     if 'cart' not in request.session:
# #         request.session['cart'] = {}
    
# #     cart = request.session['cart']
    
# #     # Add or update goods in cart
# #     if goods_id in cart:
# #         cart[goods_id] += quantity
# #     else:
# #         cart[goods_id] = quantity


    
# #     # Save cart to session
# #     request.session.modified = True
    
# #     return JsonResponse({'status': 1, 'msg': '添加成功'})


# # models.py
# from django.db import models
# from django.contrib.auth.models import User
# # from .product_models import Product  # 假设您的 Product 模型在这里

# class Cart(models.Model):
#     user = models.OneToOneField(User, on_delete=models.CASCADE)
#     created_at = models.DateTimeField(auto_now_add=True)
#     updated_at = models.DateTimeField(auto_now=True)

#     def __str__(self):
#         return f"Cart for {self.user.username}"

# class CartItem(models.Model):
#     cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items')
#     product = models.ForeignKey(Product, on_delete=models.CASCADE)
#     quantity = models.IntegerField(default=1)
#     price = models.DecimalField(max_digits=10, decimal_places=2)
#     added_at = models.DateTimeField(auto_now_add=True)

#     def __str__(self):
#         return f"{self.quantity} of {self.product.name}"
    
# # views.py
# from django.shortcuts import get_object_or_404, redirect
# from django.contrib.auth.decorators import login_required
# from .models import Cart, CartItem, Product

# # @login_required
# # def add_to_cart(request, product_id):
# #     product = get_object_or_404(Product, id=product_id)
# #     cart, created = Cart.objects.get_or_create(user=request.user)
    
# #     # 检查购物车中是否已存在该商品项
# #     cart_item, created = CartItem.objects.get_or_create(
# #         cart=cart,
# #         product=product,
# #         defaults={'quantity': 1, 'price': product.price}
# #     )
    
# #     if not created:
# #         # 如果已存在，则增加数量
# #         cart_item.quantity += 1
# #         cart_item.save()
    
# #     return redirect('product_detail', id=product_id)  # 重定向回商品详情页面    
# @login_required
# def add_to_cart(request, product_id):
#     product = get_object_or_404(Product, id=product_id)
#     cart, created = Cart.objects.get_or_create(user=request.user)
    
#     cart_item, created = CartItem.objects.get_or_create(
#         cart=cart,
#         product=product,
#         defaults={'quantity': 1, 'price': product.price}
#     )
    
#     if not created:
#         cart_item.quantity += 1
#         cart_item.save()
    
#     return redirect('product_detail', id=product_id)